package com.corecmd.tcloud.tcimserver.controller;

import com.corecmd.tcloud.tcimserver.domain.*;
import com.corecmd.tcloud.tcimserver.enums.AvailableStatusEnum;
import com.corecmd.tcloud.tcimserver.enums.FriendAddReqSuggestionEnum;
import com.corecmd.tcloud.tcimserver.enums.FriendRelationStatusEnum;
import com.corecmd.tcloud.tcimserver.service.IFriendService;
import com.corecmd.tcloud.tcimserver.service.IUserService;
import com.corecmd.tcloud.tcimserver.utils.CustomResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/25
 * @description :
 **/
@Slf4j
@Api(tags = "好友接口")
@RestController
@RequestMapping(value = "/rest/friends")
public class FriendsController extends BaseController{
    @Autowired
    private IFriendService friendService;
    @Autowired
    private IUserService userService;


    @ApiOperation("添加好友")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "friendId",value = "好友ID",dataType = "int",required = true),
            @ApiImplicitParam(paramType = "query",name = "remarkName",value = "备注昵称",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "query",name = "extraMessage",value = "附加信息",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "query",name = "groupId",value = "好友分组id",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "header",name = "authToken",value = "登录Token",dataType = "String",required = true),
    })
    public CustomResponse addFriend(@RequestParam int friendId,@RequestParam String remarkName, @RequestParam String extraMessage, @RequestParam String groupId, @RequestHeader String authToken
            , HttpServletRequest request, HttpServletResponse response){
        CustomResponse customResponse = null;
        UserInfoDTO sessionUser = getTokenUser(authToken, request, response);
        if (null != sessionUser){
            Map<String,Object> query = new HashMap<>(1);
            //判断是否已经添加过好友了
            query.put("friendId",friendId);
            query.put("relationStatus", FriendRelationStatusEnum.NORMAL.getTypeEn());
            List<ImFriendDTO> alreadyAddFriends = friendService.getFriends(sessionUser,query);
            if (null != alreadyAddFriends && alreadyAddFriends.size() > 0){
                customResponse = CustomResponse.error(CustomResponse.CODE_REQ_ERROR,"对方已经是您的好友了，请勿重复添加");
            } else {
                query.put("relationStatus", FriendRelationStatusEnum.UNAGREE.getTypeEn());
                List<ImFriendDTO> unAgreeFriends = friendService.getFriends(sessionUser,query);
                if (null != unAgreeFriends && unAgreeFriends.size() > 0){
                    customResponse = CustomResponse.error(CustomResponse.CODE_REQ_ERROR,"您已经发送过添加请求了，请等待对方处理");
                } else {
                    //查询分组是否存在
                    query.clear();
                    query.put("groupId",groupId);
                    List<ImFriendGroupDTO> groupInfo = friendService.getGroups(sessionUser, query);
                    UserInfoDTO friendInfo = userService.getUser(friendId);
                    if (null != groupInfo){
                        if (null != friendInfo){
                            int addResult = friendService.addFriend(sessionUser, friendInfo, remarkName, groupId,extraMessage);
                            customResponse = addResult>0?CustomResponse.ok("添加成功"):CustomResponse.error("添加失败");
                        }else {
                            customResponse = CustomResponse.error(CustomResponse.CODE_NOTFOUND,"好友账号不存在，添加失败");
                        }
                    } else {
                        customResponse = CustomResponse.error(CustomResponse.CODE_NOTFOUND,"分组不存在，好友添加失败");
                    }
                }
            }
        } else {
            customResponse = CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"登录Token失效，请重新登录获取Token");
        }
        return customResponse;
    }

    @ApiOperation("获取好友分组")
    @RequestMapping(value = "/group/list",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "pageNum",value = "当前页",dataType = "int",required = true),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value = "分页大小",dataType = "int",required = true),
            @ApiImplicitParam(paramType = "query",name = "searchParam",value = "模糊查询参数",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "header",name = "authToken",value = "登录token",dataType = "String",required = true),
    })
    public CustomResponse getFriendGroups(@RequestParam int pageNum, @RequestParam int pageSize, @RequestParam(required = false) String searchParam
            , @RequestHeader String authToken, HttpServletRequest request, HttpServletResponse response){
        CustomResponse customResponse = null;
        UserInfoDTO sessionUser = getTokenUser(authToken,request,response);
        if (null != sessionUser){
            Map<String,Object> query = new HashMap<String, Object>(16);
            query.put("searchParam",searchParam);
            PageHelper.startPage(pageNum,pageSize);
            List<ImFriendGroupDTO> friendGroupDTOS = friendService.getGroups(sessionUser,query);
            PageInfo<ImFriendGroupDTO> pager = new PageInfo<ImFriendGroupDTO>(friendGroupDTOS);
            customResponse = CustomResponse.ok();
            customResponse.put("pageNum",pageNum);
            customResponse.put("pageSize",pageSize);
            customResponse.put("friendGroups",pager.getList());
            customResponse.put("totalRecord",pager.getTotal());
            customResponse.put("totalPage",pager.getPages());
        } else {
            customResponse = CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"登录Token失效，请重新登录获取Token");
        }
        return customResponse;
    }

    @ApiOperation("添加好友分组")
    @RequestMapping(value = "/group/add",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "groupName",value = "分组名称",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "header",name = "authToken",value = "登录token",dataType = "String",required = true),
    })
    public CustomResponse addFriendGroup(@RequestParam String groupName,@RequestHeader String authToken, HttpServletRequest request, HttpServletResponse response){
        CustomResponse customResponse = null;
        UserInfoDTO sessionUser = getTokenUser(authToken,request,response);
        if (null != sessionUser){
            int addResult = friendService.addGroup(sessionUser,groupName);
            customResponse = addResult>0?CustomResponse.ok("添加成功"):CustomResponse.error("添加失败");
        } else {
            customResponse = CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"登录Token失效，请重新登录获取Token");
        }
        return customResponse;
    }

    @ApiOperation("重命名好友分组")
    @RequestMapping(value = "/group/rename",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "groupId",value = "分组id",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "query",name = "newName",value = "新分组名称",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "header",name = "authToken",value = "登录token",dataType = "String",required = true),
    })
    public CustomResponse renameFriendGroup(@RequestParam String groupId,@RequestParam String newName,@RequestHeader String authToken, HttpServletRequest request, HttpServletResponse response){
        CustomResponse customResponse = null;
        UserInfoDTO sessionUser = getTokenUser(authToken,request,response);
        if (null != sessionUser){
            Map<String,Object> query = new HashMap<>(1);
            query.put("groupId",groupId);
            List<ImFriendGroupDTO> groupInfo = friendService.getGroups(sessionUser,query);
            if (null != groupInfo){
                int renameResult = friendService.renameGroup(sessionUser,groupId,newName);
                customResponse = renameResult>0?CustomResponse.ok("重命名成功"):CustomResponse.error("重命名失败");
            } else {
                customResponse = CustomResponse.error(CustomResponse.CODE_NOTFOUND,"分组不存在，重命名失败");
            }
        } else {
            customResponse = CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"登录Token失效，请重新登录获取Token");
        }
        return customResponse;
    }

    @ApiOperation("删除好友分组")
    @RequestMapping(value = "/group/remove",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "groupId",value = "分组id",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "header",name = "authToken",value = "登录token",dataType = "String",required = true),
    })
    public CustomResponse deleteFriendGroup(@RequestParam String groupId,@RequestHeader String authToken, HttpServletRequest request, HttpServletResponse response){
        CustomResponse customResponse = null;
        UserInfoDTO sessionUser = getTokenUser(authToken,request,response);
        if (null != sessionUser){
            Map<String,Object> query = new HashMap<>(1);
            query.put("groupId",groupId);
            List<ImFriendGroupDTO> groupInfo = friendService.getGroups(sessionUser,query);
            if (null != groupInfo){
                boolean isDefaultGroup = groupInfo.get(0).getDefaultGroup() == AvailableStatusEnum.YES.getCode();
                if (!isDefaultGroup){
                    int removeResult = friendService.removeGroup(sessionUser,groupId);
                    customResponse = removeResult>0?CustomResponse.ok("删除成功"):CustomResponse.error("删除失败");
                } else {
                    customResponse = CustomResponse.error(CustomResponse.CODE_REQ_ERROR,"默认分组不允许删除");
                }
            } else {
                customResponse = CustomResponse.error(CustomResponse.CODE_NOTFOUND,"分组不存在，删除失败");
            }
        } else {
            customResponse = CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"登录Token失效，请重新登录获取Token");
        }
        return customResponse;
    }

    @ApiOperation("处理某用户的好友申请")
    @RequestMapping(value = "/friendReq/process/{senderId}",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path",name = "senderId",value = "申请人id",dataType = "int",required = true),
            @ApiImplicitParam(paramType = "query",name = "suggestion",value = "处理意见 0：同意 1：拒绝",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "header",name = "authToken",value = "登录token",dataType = "String",required = true),
    })
    public CustomResponse processFriendReq(@PathVariable int senderId, @RequestParam String suggestion,@RequestHeader String authToken, HttpServletRequest request, HttpServletResponse response){
        CustomResponse customResponse = null;
        UserInfoDTO sessionUser = getTokenUser(authToken,request,response);
        if (null != sessionUser){
            Map<String,Object> query = new HashMap<String,Object>();
            query.put("senderId",senderId);
            query.put("status","1");
            List<ImFriendAddRequestDTO> friendAddRequestDOS = friendService.listFriendReqs(sessionUser,query);
            if (null != friendAddRequestDOS && friendAddRequestDOS.size() > 0){
                FriendAddReqSuggestionEnum suggestionEnum = FriendAddReqSuggestionEnum.match(suggestion);
                if (null != suggestionEnum){
                    int result = friendService.processFriendAddReq(sessionUser,senderId,suggestionEnum);
                    customResponse = result > 0 ? CustomResponse.ok("处理成功") : CustomResponse.error("处理失败");
                } else {
                    customResponse = CustomResponse.error(CustomResponse.CODE_REQ_ERROR,"处理意见不正确；0：同意 1：拒绝");
                }
            } else {
                customResponse = CustomResponse.error(CustomResponse.CODE_REQ_ERROR,"没有待处理的好友请求");
            }
        } else {
            customResponse = CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"登录Token失效，请重新登录获取Token");
        }
        return customResponse;
    }

    @ApiOperation("加载好友申请列表")
    @RequestMapping(value = "/friendReq/list",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "pageNum",value = "当前页",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value = "分页大小",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "query",name = "status",value = "状态 0：已同意 1：未同意 2：已拒绝",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "query",name = "type",value = "类型 0:我发起的  1：加我的",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "query",name = "searchParam",value = "模糊查询参数",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "header",name = "authToken",value = "登录token",dataType = "String",required = true),
    })
    public CustomResponse listFriendReq(@RequestParam int pageNum, @RequestParam int pageSize, @RequestParam String status, @RequestParam String type, @RequestParam String searchParam
            ,@RequestHeader String authToken, HttpServletRequest request, HttpServletResponse response){
        CustomResponse customResponse = null;
        UserInfoDTO sessionUser = getTokenUser(authToken,request,response);
        if (null != sessionUser){
            Map<String,Object> query = new HashMap<String,Object>();
            query.put("status",status);
            query.put("searchParam",searchParam);
            query.put("type",type);
            PageHelper.startPage(pageNum,pageSize);
            List<ImFriendAddRequestDTO> friendAddRequestDOS = friendService.listFriendReqs(sessionUser,query);
            PageInfo<ImFriendAddRequestDTO> pager = new PageInfo<ImFriendAddRequestDTO>(friendAddRequestDOS);
            customResponse = CustomResponse.ok();
            customResponse.put("pageNum",pageNum);
            customResponse.put("pageSize",pageSize);
            customResponse.put("friendAddReqs",pager.getList());
            customResponse.put("totalRecord",pager.getTotal());
            customResponse.put("totalPage",pager.getPages());
        } else {
            customResponse = CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"登录Token失效，请重新登录获取Token");
        }
        return customResponse;
    }

    @ApiOperation("好友列表")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "pageNum",value = "当前页",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value = "分页大小",dataType = "String",required = true),
            @ApiImplicitParam(paramType = "query",name = "searchParam",value = "模糊查询参数",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "header",name = "authToken",value = "登录token",dataType = "String",required = true),
    })
    public CustomResponse listFriends(@RequestParam int pageNum, @RequestParam int pageSize, @RequestParam String searchParam
            ,@RequestHeader String authToken, HttpServletRequest request, HttpServletResponse response){
        CustomResponse customResponse = null;
        UserInfoDTO sessionUser = getTokenUser(authToken,request,response);
        if (null != sessionUser){
            Map<String,Object> query = new HashMap<String,Object>();
            query.put("searchParam",searchParam);
            query.put("relationStatus",FriendRelationStatusEnum.NORMAL.getTypeEn());
            PageHelper.startPage(pageNum,pageSize);
            List<ImFriendDTO> friends = friendService.getFriends(sessionUser,query);
            PageInfo<ImFriendDTO> pager = new PageInfo<ImFriendDTO>(friends);
            customResponse = CustomResponse.ok();
            customResponse.put("pageNum",pageNum);
            customResponse.put("pageSize",pageSize);
            customResponse.put("friends",pager.getList());
            customResponse.put("totalRecord",pager.getTotal());
            customResponse.put("totalPage",pager.getPages());
        } else {
            customResponse = CustomResponse.error(CustomResponse.CODE_NEED_LOGIN,"登录Token失效，请重新登录获取Token");
        }
        return customResponse;
    }
}
